<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>项目节点管理</div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>

        <el-table-column
          label="节点名称"
          prop="nodeName"
          v-show="header_list[0].showTable"
        ></el-table-column>

        <el-table-column
          label="节点类型"
          prop="type"
          v-show="header_list[1].showTable"
        >
          <template #default="scope">
            <div v-for="item in type_list" :key="item.value">
              <span v-if="scope.row.type == item.value">{{ item.label }}</span>
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="按钮名称"
          prop="buttonName"
          v-show="header_list[3].showTable"
        ></el-table-column>
        <el-table-column label="状态" v-show="header_list[2].showTable">
          <template #default="scope">
            <div v-if="scope.row.status">启用</div>
            <div v-else>禁用</div>
          </template>
        </el-table-column>
        <el-table-column
          label="终止节点"
          prop="stopNodeType"
          v-show="header_list[4].showTable"
        >
          <template #default="scope">
            <div v-for="item in list" :key="item.id">
              <span v-if="item.type == scope.row.stopNodeType">{{
                item.nodeName
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <!-- <el-button @click="edit_node_list({ item: scope.row, type: 3 })"
              >节点文件配置</el-button
            > -->
            <el-button @click="edit_node_list({ item: scope.row, type: 1 })"
              >编辑</el-button
            >
            <el-button @click="edit_node_list({ item: scope.row, type: 2 })"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addnodeConfig)"
    >
      <template #title
        ><h4 v-if="add_form_data.id == ''">新增节点</h4>
        <h4 v-else>编辑节点</h4></template
      >
      <template #default>
        <el-form
          ref="addnodeConfig"
          :model="add_form_data"
          :rules="rules"
          label-width="120"
        >
          <el-form-item prop="nodeName" label="节点名称">
            <el-input
              v-model="add_form_data.nodeName"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item prop="type" label="节点类型">
            <el-select v-model="add_form_data.type">
              <el-option
                v-for="item in type_list"
                :key="item.value"
                :value="item.value"
                :label="item.label"
                :disabled="
                  list.some((i) => {
                    return i.type == item.value && i.status
                  })
                "
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="按钮名称">
            <el-input
              v-model="add_form_data.buttonName"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-radio :label="true" v-model="add_form_data.status"
              >启用</el-radio
            >
            <el-radio :label="false" v-model="add_form_data.status"
              >禁用</el-radio
            >
          </el-form-item>
          <el-form-item label="结束节点">
            <el-select v-model="add_form_data.stopNodeType">
              <el-option
                v-for="item in list"
                :key="item.type"
                :value="item.type"
                :label="item.nodeName"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addnodeConfig)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit(addnodeConfig)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { useStore } from 'vuex'
const store = useStore()
const list = ref()
const total = ref()
const max_height = ref()
const loading = ref(false)
const height_size = ref(1)
const show_box = ref()
const addnodeConfig = ref<FormInstance>()
const rules = ref({
  //   buttonName: [{ required: true, message: "请输入按钮名称", trigger: "blur" }],
  nodeName: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
})
const type_list = ref([
  { label: '项目创建', value: 1 },
  { label: '资料提交', value: 2 },
  { label: '变更单', value: 3 },
  { label: '项目完成', value: 4 },
])
const header_list = ref<any>([
  {
    label: '节点名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '节点类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: true,
    options: type_list.value,
  },
  {
    label: '按钮名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },

  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: true,
        label: '启用',
      },
      {
        value: false,
        label: '禁用',
      },
    ],
  },
  {
    label: '终止节点',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const edit_node_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      buttonName: e.item.buttonName,
      enterpriseId: add_form_data.value.enterpriseId,
      nodeName: e.item.nodeName,
      status: e.item.status,
      stopNodeType: e.item.stopNodeType,
      type: e.item.type,
    }
    show_box.value = true
  } else if (e.type == 2) {
    ElMessageBox.confirm('确定删除该记录？', '', {
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.nodeConfig + '/' + e.item.id,
            method: 'delete',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}
const page_data = ref({
  enterpriseId: computed(() => {
    return store.state.enterprise_id
  }),
  buttonName: '',
  nodeName: '',
  status: '',
  stopNodeType: '',
  type: '',
})
const add_form_data = ref({
  id: '',
  buttonName: '',
  enterpriseId: store.state.enterprise_id,
  nodeName: '',
  status: true,
  stopNodeType: '',
  type: '',
})
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  //   get_myProjectTaskList();
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('change_default_active')
})
const edit_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      buttonName: e.item.buttonName,
      enterpriseId: store.state.enterprise_id,
      nodeName: e.item.nodeName,
      status: e.item.status,
      stopNodeType: e.item.stopNodeType,
      type: e.item.type,
    }
    show_box.value = true
  } else {
    ElMessageBox.confirm('确定删除该记录？', '', {
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.nodeConfig + '/' + e.item.id,
            method: 'delete',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      let data = JSON.parse(JSON.stringify(add_form_data.value))
      axios
        .request({
          url: serviceApi.nodeConfig + (data.id == '' ? '' : '/' + data.id),
          method: data.id == '' ? 'post' : 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  let data = handle_search_key(page_data.value)
  axios
    .request({
      url: serviceApi.nodeConfig + '/list',
      method: 'post',
      data: data,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    enterpriseId: page_data.value.enterpriseId,
    type: header_list.value[1].value,
    nodeName: header_list.value[0].value,
    buttonName: header_list.value[2].value,
    status:
      header_list.value[3].value == ''
        ? ''
        : !header_list.value[3].value
        ? false
        : header_list.value[3].value,
    stopNodeType: header_list.value[4].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    buttonName: '',
    enterpriseId: store.state.enterprise_id,
    nodeName: '',
    status: true,
    stopNodeType: '',

    type: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
